﻿<%@ WebHandler Language="C#" Class="StepCheckPointResultEditHandler" %>
/*
 * Description: 工序检测项修改调整处理程序
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer: longb 
 * create Date:2024.10.22
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Configuration;
using System.Text;

public class StepCheckPointResultEditHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    uMESContainerInfoPrintIBusiness oIBusiness = uMESBusinessFactory.instance.GetContainerInfoPrintObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "initPageData":
                    initPageData(context);
                    break;
                case "GetContainerData":
                    GetContainerData(context);
                    break;
                case "GetStepCheckListData"://获取工序检测项基础数据及其录入结果 
                    GetStepCheckListData(context);
                    break;
                case "SaveStepCheckPointRecordData"://检测项结果调整修改记录数据保存 
                    SaveStepCheckPointResultUpdateRecordData(context);
                    break;
                case "AuditCheckPointResultUpdate"://检测项结果调整修改记录数据(审批)
                    AuditCheckPointResultUpdate(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


    private void initPageData(HttpContext context)
    {
        DataTable wcdt = m_CommonObj.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        DataTable dt = m_CommonObj.GetFactory(new Dictionary<string, string>());
        DataView temView = dt.DefaultView;
        temView.RowFilter = "(FactoryName  like '%机匣%') or (FactoryName like '%结构件%') or (FactoryName like '%盘轴%') or (FactoryName like '%钣焊%') or (FactoryName like '%装配试车%')  or (FactoryName like '%叶片%') or (FactoryName like '%热表%') or (FactoryName like '%工装%')";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = true;
        result.DBTable = wcdt;
        result.ReturnData = temView.ToTable();
        context.Response.Write(JsonConvert.SerializeObject(result));
    }


    private void GetContainerData(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"]);
        var oQuery = new Dictionary<string, string>();
        oQuery.Add("PageSize", context.Request["pageSize"]);
        oQuery.Add("CurrentPageIndex", context.Request["pageNumber"]);
        oQuery.Add("EmployeeName", string.IsNullOrWhiteSpace(para["txtEmployeeName"]) ? m_UserInfo.FullName : para["txtEmployeeName"]);
        if (!string.IsNullOrWhiteSpace(para["txtFactory"]))
        {
            oQuery.Add("FactoryName", para["txtFactory"]);
        }
        if (!string.IsNullOrWhiteSpace(para["txtContainer"]))
        {
            oQuery.Add("ContainerName", para["txtContainer"]);
        }
        if (!string.IsNullOrWhiteSpace(para["txtProduct"]))
        {
            oQuery.Add("ProductName", para["txtProduct"]);
        }
        if (!string.IsNullOrWhiteSpace(para["txtWorkcenter"]))
        {
            oQuery.Add("WorkcenterName", para["txtWorkcenter"]);
        }
        if (!string.IsNullOrWhiteSpace(para["txtMfgOrder"]))
        {
            oQuery.Add("MfgOrderNames", "'" + para["txtMfgOrder"] + "'");
            var cpara = new Dictionary<string, string>();
            cpara.Add("FaMfgOrderName", para["txtMfgOrder"]);
            cpara.Add("FactoryID", m_UserInfo.FactoryID);
            DataTable dt = oIBusiness.GetSonMfgOrder(cpara);
            while (dt.Rows.Count > 0)
            {
                DataTable sonDt = dt.Clone();
                foreach (DataRow _row in dt.Rows)
                {
                    oQuery["MfgOrderNames"] += String.Format(",'{0}'", _row["mfgordername"].ToString());
                    cpara["FaMfgOrderName"] = _row["mfgordername"].ToString();
                    DataTable _dt = oIBusiness.GetSonMfgOrder(cpara);// '查询子订单下的子订单
                    sonDt.Merge(_dt);
                }
                dt = sonDt;
            }
        }

        if (!string.IsNullOrWhiteSpace(para["txtStartDate"]))
        {
            oQuery.Add("StartDate", para["txtStartDate"]);
        }
        if (!string.IsNullOrWhiteSpace(para["txtEndDate"]))
        {
            oQuery.Add("EndDate", para["txtEndDate"]);
        }
        if (!string.IsNullOrWhiteSpace(para["txtPrintType"]))//是否领料
        {
            oQuery.Add("IsselfMfg", para["txtPrintType"]);
        }
        oQuery.Add("type", context.Request["type"]);
        uMESProcessResult result = oIBusiness.GetContainerCurrentInfo(oQuery);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void GetStepCheckListData(HttpContext context)
    {
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"]);
        var sql = @" select ws.workflowstepname,sc.name,sc.checkpointnote,sc.checkpointnotedis,sc.drawingrequire,sc.drawingrequiredis,sc.bubblenumber, 
             scr.workcheckpointresultnote,scr.workcheckpointresultnotedis,scr.checkpointresultnote,scr.checkpointresultnotedis,scr.stepcheckpointresultid,
             c.oldworkcheckpointresultnote,c.oldcheckpointresultnote,c.newworkcheckpointresultnote,c.newcheckpointresultnote,
             e.fullname  auditname,to_char(c.audittime,'yyyy-mm-dd hh24:mi:ss') audittime,nvl(c2.cn,0) cn,nvl(c3.acn,0) acn,c.id,c.note,c.auditresult,
             e2.fullname  updatename,to_char(c.updatetime,'yyyy-mm-dd hh24:mi:ss') updatetime
             from workflowstep ws 
             left join specbase sb on sb.specbaseid=ws.specbaseid
             left join spec s on s.specid=nvl(sb.revofrcdid,ws.specid)----子工艺的工序
             left join stepcheckpoint sc on sc.workflowstepid =ws.workflowstepid
             left join stepcheckpointresult scr on scr.stepcheckpointid =sc.stepcheckpointid and scr.containerid ='{2}'
             left join checkpointresultupdaterecord c on c.stepcheckpointresultid =scr.stepcheckpointresultid and nvl(c.isuse,0)=0
             left join (select count(1) cn,stepcheckpointresultid from  checkpointresultupdaterecord
                    where isuse=0--auditempid is not null and auditresult='同意'             
                    group by stepcheckpointresultid
                    ) c2 on c2.stepcheckpointresultid=scr.stepcheckpointresultid
             left join (select count(1) acn,stepcheckpointresultid from  checkpointresultupdaterecord
                    where auditresult='同意'             
                    group by stepcheckpointresultid
                    ) c3 on c3.stepcheckpointresultid=scr.stepcheckpointresultid
             left join employee e on e.employeeid =c.auditempid
             left join employee e2 on e2.employeeid =c.updateempid                
             where ws.workflowid in ('{0}','{1}') and sc.bubblenumber like '<%'
             order by s.specno,sc.bubblenumber 
            ";
        sql = string.Format(sql, para["FAWORKFLOWID"], para["WORKFLOWID"], para["CONTAINERID"]);
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        uMESProcessResult result = new uMESProcessResult();
        result.Result = dt.Rows.Count > 0;
        result.DBTable = dt;
        result.Message = result.Result ? "" : "查询不到相关数据";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void SaveStepCheckPointResultUpdateRecordData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"]);
        var container = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["container"]);
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format("select count(1) CN from checkpointresultupdaterecord where stepcheckpointresultid='{0}' and auditresult='同意'", para["STEPCHECKPOINTRESULTID"]));
        if (dt.Rows.Count > 0)
        {
            //if (Convert.ToInt32(dt.Rows[0]["CN"].ToString()) >= 2)
            //{
            //    result.Message = "当前检测项已审批2次，禁止再调整";
            //    context.Response.Write(JsonConvert.SerializeObject(result));
            //    return;
            //}
        }
        var sql2 = @" select count(1) CN from stepcheckpointresult scr 
            inner join checkpointresultupdaterecord c on c.stepcheckpointresultid =scr.stepcheckpointresultid 
            where scr.containerid='{0}' and c.isuse=0 ";
        DataTable dt2 = DatabaseHelper.Query_ReturnDatTable(string.Format(sql2, container["CONTAINERID"]));
        DataTable dt3 = DatabaseHelper.Query_ReturnDatTable(string.Format("select count(1) CN from checkpointresultupdaterecord where stepcheckpointresultid='{0}' and isuse=0", para["STEPCHECKPOINTRESULTID"]));
        if (dt2.Rows.Count > 0 && Convert.ToInt32(dt3.Rows[0]["CN"].ToString()) == 0)
        {
            //if (Convert.ToInt32(dt2.Rows[0]["CN"].ToString()) >= 2)
            //{
            //    result.Message = "该批次检测项记录已存在两条修改记录，禁止再调整";
            //    context.Response.Write(JsonConvert.SerializeObject(result));
            //    return;
            //}
        }

        var sql = @"begin
        update checkpointresultupdaterecord set isuse=1 where stepcheckpointresultid='{0}';         
        insert into checkpointresultupdaterecord(stepcheckpointresultid,oldworkcheckpointresultnote,oldcheckpointresultnote,newcheckpointresultnote,updateempid,updatetime)
        values('{0}','{1}','{2}','{3}','{4}',sysdate());
        end;";
        sql = string.Format(sql, para["STEPCHECKPOINTRESULTID"], para["WORKCHECKPOINTRESULTNOTEDIS"], para["CHECKPOINTRESULTNOTEDIS"], para["strCode"], m_UserInfo.EmployeeID);
        var cc = DatabaseHelper.ExecuteSql(sql);
        result.Result = cc > 0;
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void AuditCheckPointResultUpdate(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        if (!m_UserInfo.Roles.Contains("检验室室主任") || !m_UserInfo.Roles.Contains("检验分室主任"))
        {
            //result.Message = "当前登录人非检验室室主任或检验分室主任，无权审批此功能";
            //context.Response.Write(JsonConvert.SerializeObject(result));
            //return;
        }

        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"]);
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["para"]);
        var arrList = new ArrayList();
        foreach (DataRow row in dt.Rows)
        {
            if (para["isok"].Equals("0"))
            {
                arrList.Add(string.Format("update stepcheckpointresult set checkpointresultnotedis='{0}' where stepcheckpointresultid='{1}'", row["newcheckpointresultnote"], row["stepcheckpointresultid"]));
            }
            arrList.Add(string.Format("update checkpointresultupdaterecord set auditempid='{0}',audittime=sysdate,note='{2}',auditresult='{3}' where id='{1}'", m_UserInfo.EmployeeID, row["id"], para["note"], para["isok"].Equals("0") ? "同意" : "不同意"));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
        result.Message = result.Result ? "审核成功" : "审核失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
}